"""
邮件模板数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean, Index, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base


class EmailTemplate(Base):
    """邮件模板模型"""
    __tablename__ = "email_templates"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="模板名称")
    subject = Column(String(500), nullable=False, comment="邮件主题")
    content = Column(Text, nullable=False, comment="邮件内容")
    template_type = Column(String(20), nullable=False, default="html", comment="模板类型")
    category = Column(String(50), nullable=False, default="custom", comment="模板分类")
    description = Column(Text, nullable=True, comment="模板描述")
    variables = Column(JSON, nullable=True, comment="模板变量列表")
    is_active = Column(Boolean, nullable=False, default=True, comment="是否启用")

    # 关联字段
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关系
    user = relationship("User", back_populates="email_templates")

    # 索引
    __table_args__ = (
        Index('idx_email_templates_user_name', 'user_id', 'name'),
        Index('idx_email_templates_user_category', 'user_id', 'category'),
        Index('idx_email_templates_user_active', 'user_id', 'is_active'),
        Index('idx_email_templates_created_at', 'created_at'),
    )

    def __repr__(self):
        return f"<EmailTemplate(id={self.id}, name='{self.name}', type='{self.template_type}')>"
